import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref('')
  const role = ref('')

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    role.value = info?.role || ''
  }

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除用户信息
  const clearUserInfo = () => {
    userInfo.value = null
    token.value = ''
    role.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 从localStorage加载用户信息
  const loadUserInfoFromStorage = () => {
    const storedToken = localStorage.getItem('token')
    const storedUserInfo = localStorage.getItem('userInfo')
    
    if (storedToken) {
      token.value = storedToken
    }
    
    if (storedUserInfo) {
      try {
        userInfo.value = JSON.parse(storedUserInfo)
        role.value = userInfo.value?.role || ''
      } catch (e) {
        console.error('解析用户信息失败:', e)
        clearUserInfo()
      }
    }
  }

  // 更新用户头像
  const updateUserAvatar = (avatarUrl) => {
    if (userInfo.value) {
      userInfo.value.avatar = avatarUrl
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  // 更新用户基本信息
  const updateUserBasicInfo = (name, phone) => {
    if (userInfo.value) {
      userInfo.value.name = name
      userInfo.value.phone = phone
      localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
    }
  }

  return {
    userInfo,
    token,
    role,
    setUserInfo,
    setToken,
    clearUserInfo,
    loadUserInfoFromStorage,
    updateUserAvatar,
    updateUserBasicInfo
  }
})
